package com.qiaoba.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.qiaoba.api.auth.entity.dto.RoleDTO;
import com.qiaoba.api.system.entity.vo.SysRoleVO;
import com.qiaoba.api.system.entity.vo.SysUserVO;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.module.system.converter.SysRoleConverter;
import com.qiaoba.module.system.entity.SysRole;
import com.qiaoba.module.system.entity.SysUserRole;
import com.qiaoba.module.system.entity.param.SysRoleParam;
import com.qiaoba.module.system.entity.param.SysUserRoleParam;
import com.qiaoba.module.system.mapper.SysUserRoleMapper;
import com.qiaoba.module.system.service.SysRoleService;
import com.qiaoba.module.system.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色关联 服务层实现
 *
 * @author ailanyin
 * @date 2023-09-13 18:31:00
 */
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl implements SysUserRoleService {

    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysRoleService sysRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(String userId, Set<String> roleIds, boolean isUpdate) {
        if (isUpdate) {
            deleteByUserId(userId);
        }
        if (CollUtil.isEmpty(roleIds)) {
            return;
        }
        List<SysUserRole> list = new ArrayList<>();
        for (String role : roleIds) {
            list.add(new SysUserRole(userId, role));
        }
        insertBatch(list);
    }

    @Override
    public void insertBatch(List<SysUserRole> list) {
        Db.saveBatch(list);
    }

    @Override
    public void deleteByUserId(String userId) {
        sysUserRoleMapper.delete(createWrapper(userId));
    }

    @Override
    public void deleteByUserIds(List<String> userIds) {
        sysUserRoleMapper.deleteByUserIds(userIds);
    }

    @Override
    public void deleteByRoleIdAndUserIds(String roleId, List<String> userIds) {
        sysUserRoleMapper.deleteByRoleIdAndUserIds(roleId, userIds);
    }

    @Override
    public List<String> selectRoleIdsByUserId(String userId, String status) {
        return sysUserRoleMapper.selectRoleIdsByUserId(userId, status);
    }

    @Override
    public List<SysRoleVO> selectRolesByUserId(String userId, String status) {
        List<String> hasRoleIds = selectRoleIdsByUserId(userId, status);
        List<SysRole> roles = sysRoleService.selectList(new SysRoleParam());
        List<SysRoleVO> list = new ArrayList<>();
        for (SysRole role : roles) {
            list.add(SysRoleConverter.domain2Vo(role, CollUtil.isNotEmpty(hasRoleIds) && hasRoleIds.contains(role.getRoleId())));
        }
        return list;
    }

    @Override
    public List<RoleDTO> selectRoleDtoByUserId(String userId, String status) {
        return sysUserRoleMapper.selectRoleListByUserId(userId, status);
    }

    @Override
    public void insertAuthUsers(String roleId, List<String> userIds) {
        List<SysUserRole> list = new ArrayList<>();
        for (String userId : userIds) {
            list.add(new SysUserRole(userId, roleId));
        }
        Db.saveBatch(list);
    }

    @Override
    public String selectRoleGroup(String userId) {
        List<RoleDTO> list = selectRoleDtoByUserId(userId, BaseConstant.NORMAL);
        List<String> names = list.stream().map(RoleDTO::getRoleName).collect(Collectors.toList());
        return CollUtil.isNotEmpty(list) ? StrUtil.join(BaseConstant.LINE_JOIN_STR, names) : StrUtil.EMPTY;
    }

    @Override
    public List<SysUserVO> selectAllocatedList(SysUserRoleParam param) {
        return sysUserRoleMapper.selectAllocatedList(param);
    }

    @Override
    public List<SysUserVO> selectUnallocatedList(SysUserRoleParam param) {
        return sysUserRoleMapper.selectUnallocatedList(param);
    }

    private QueryWrapper<SysUserRole> createWrapper(String userId) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(SysUserRole::getUserId, userId);
        return wrapper;
    }
}
